/**
 * 日志服务类
 */
export class LogService {
  // 格式化日志级别
  static formatLevel(level) {
    const levelMap = {
      'Error': '错误',
      'Warning': '警告', 
      'Info': '信息',
      'Debug': '调试'
    }
    return levelMap[level] || level
  }
  
  // 获取日志级别颜色
  static getLevelColor(level) {
    const colorMap = {
      'Error': '#f56c6c',
      'Warning': '#e6a23c',
      'Info': '#409eff',
      'Debug': '#67c23a'
    }
    return colorMap[level] || '#909399'
  }
  
  // 获取日志级别标签类型
  static getLevelTagType(level) {
    const typeMap = {
      'Error': 'danger',
      'Warning': 'warning',
      'Info': 'info',
      'Debug': 'success'
    }
    return typeMap[level] || 'info'
  }
  
  // 格式化时间
  static formatDateTime(timestamp) {
    if (!timestamp) return '-'
    return new Date(timestamp).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  
  // 格式化相对时间
  static formatRelativeTime(timestamp) {
    if (!timestamp) return '-'
    
    const now = new Date()
    const time = new Date(timestamp)
    const diff = now - time
    
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)
    
    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    
    return this.formatDateTime(timestamp)
  }
  
  // 格式化JSON字符串
  static formatJSON(jsonStr) {
    try {
      if (typeof jsonStr === 'string') {
        const obj = JSON.parse(jsonStr)
        return JSON.stringify(obj, null, 2)
      } else {
        return JSON.stringify(jsonStr, null, 2)
      }
    } catch (e) {
      return jsonStr
    }
  }
  
  // 截断文本
  static truncateText(text, maxLength = 100) {
    if (!text) return ''
    if (text.length <= maxLength) return text
    return text.substring(0, maxLength) + '...'
  }
  
  // 高亮搜索关键字
  static highlightKeyword(text, keyword) {
    if (!keyword || !text) return text
    
    const regex = new RegExp(`(${keyword})`, 'gi')
    return text.replace(regex, '<mark>$1</mark>')
  }
  
  // 解析异常堆栈
  static parseStackTrace(exception) {
    if (!exception) return null
    
    const lines = exception.split('\n')
    const result = {
      message: lines[0] || '',
      stackTrace: lines.slice(1).map(line => {
        const match = line.trim().match(/at\s+(.+)\s+in\s+(.+):line\s+(\d+)/)
        if (match) {
          return {
            method: match[1],
            file: match[2],
            line: match[3],
            raw: line.trim()
          }
        }
        return { raw: line.trim() }
      }).filter(item => item.raw)
    }
    
    return result
  }
  
  // 生成日志搜索过滤器
  static createLogFilter(searchForm) {
    return (log) => {
      // 级别筛选
      if (searchForm.level && log.level !== searchForm.level) {
        return false
      }
      
      // 关键字搜索
      if (searchForm.keyword) {
        const keyword = searchForm.keyword.toLowerCase()
        const searchableText = [
          log.message,
          log.exception,
          log.logEvent,
          log.properties
        ].join(' ').toLowerCase()
        
        if (!searchableText.includes(keyword)) {
          return false
        }
      }
      
      // 时间范围筛选
      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        const logTime = new Date(log.timestamp)
        const startTime = new Date(searchForm.dateRange[0])
        const endTime = new Date(searchForm.dateRange[1])
        
        if (logTime < startTime || logTime > endTime) {
          return false
        }
      }
      
      return true
    }
  }
  
  // 导出日志为CSV格式
  static exportToCSV(logs) {
    const headers = ['ID', '级别', '时间', '消息', '事件类型', '异常信息']
    const csvContent = [
      headers.join(','),
      ...logs.map(log => [
        log.id,
        log.level,
        this.formatDateTime(log.timestamp),
        `"${log.message.replace(/"/g, '""')}"`,
        log.logEvent || '',
        log.exception ? `"${log.exception.replace(/"/g, '""')}"` : ''
      ].join(','))
    ].join('\n')
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    
    link.setAttribute('href', url)
    link.setAttribute('download', `logs_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
  
  // 导出日志为JSON格式
  static exportToJSON(logs) {
    const jsonContent = JSON.stringify(logs, null, 2)
    const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    
    link.setAttribute('href', url)
    link.setAttribute('download', `logs_${new Date().toISOString().slice(0, 10)}.json`)
    link.style.visibility = 'hidden'
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
  
  // 获取日志级别统计
  static getLogLevelStats(logs) {
    const stats = {
      total: logs.length,
      error: 0,
      warning: 0,
      info: 0,
      debug: 0
    }
    
    logs.forEach(log => {
      switch (log.level) {
        case 'Error':
          stats.error++
          break
        case 'Warning':
          stats.warning++
          break
        case 'Info':
          stats.info++
          break
        case 'Debug':
          stats.debug++
          break
      }
    })
    
    return stats
  }
}

// 导出默认实例
export default new LogService()
